/**
 * @description 服务查询条件配置-queryConditionConfig.jsp
 * @author guoyanfei
 * @date 2017/11/23
 */
// 项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";
var serviceId = GetQueryString("serviceId");
var serviceType = GetQueryString("serviceType");
var grade = GetQueryString("grade");

$(function () {
    $("#serviceId").val(serviceId);
    $("#serviceType").val(serviceType);
    $("#grade").val(grade);
    /*****************Begin 动态查询列配置**********************/
    //查询显示字段列表
    $("#tb_queryfieldList").bootstrapTable('destroy').bootstrapTable({
        url: postPath + '/system/queryfield/getQueryFieldList',
        undefinedText: '-',
        striped: true, // 是否显示行间隔色
        queryParams: {serviceId: serviceId, serviceType: serviceType, grade: grade, paramType: 1},
        showColumns: false, // 显示隐藏列
        showRefresh: false, // 显示刷新按钮
        uniqueId: "guid", // 每一行的唯一标识
        columns: [{
            field: 'state',
            checkbox: true,
            align: 'center',
            valign: 'middle'
        }, {
            title: '字段Code',
            field: 'fieldname',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '字段名称',
            field: 'fieldnameCn',
            align: 'left',
            valign: 'middle',
            sortable: false
        }, {
            title: '字段类型',
            field: 'fieldtype',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '参数Code',
            field: 'parametercode',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '参数条件',
            field: 'parametercondition',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '参数格式化',
            field: 'paramformat',
            align: 'center',
            valign: 'middle',
            sortable: false,
            visible: false,
        }, {
            title: '显示类型',
            field: 'showtype',
            align: 'left',
            valign: 'middle',
            sortable: false,
            visible: false,
            formatter: function (value, row, index) {
                var result = "";
                if (value == 0) {
                    result = "文本框";
                } else if (value == 1) {
                    result = "下拉框";
                } else if (value == 2) {
                    result = "单选按钮";
                } else if (value == 3) {
                    result = "复选框";
                } else if (value == 4) {
                    result = "日期框";
                }
                return result;
            }
        }, {
            title: '显示顺序',
            field: 'queryorder',
            align: 'left',
            valign: 'middle',
            width: '100px',
            sortable: false,
            visible: false,
        }]
    });


    //删除查询字段
    $("#btn_queryDel").click(function () {
        var row = $('#tb_queryfieldList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        }

        var message = "";
        row.forEach(e => {
             message += e.fieldname + ", " + e.fieldnameCn + "<br/>"
        });

        var deleteFunction = function (result) {
            if (result == false)
                return;
            var keys = "";
            $.each(row, function (i, e) {
                keys += e.guid + "@";
            });
            keys = keys.substring(0, keys.length - 1);
            $.ajax({
                url: postPath + '/system/queryfield/deleteQueryfield',
                type: 'POST',
                data: {guids: keys, serviceId: serviceId},
                success: function (res) {
                    if (res > 0) {
                        $('#tb_queryfieldList').bootstrapTable('refresh');
                        getQuerysql();
                        // bootbox.alert("删除成功!");
                        showMsg('删除成功!', 'success');
                    } else {
                        // bootbox.alert("删除失败!");
                        showMsg('删除失败!', 'error');
                    }
                },
                error: function () {
                    // bootbox.alert("删除失败!");
                    showMsg('删除失败!', 'error');
                }
            });
        };

        confirmDelete( message, deleteFunction);
    });

    //新增查询字段操作
    $("#btn_queryAdd").click(function () {
        var frameSrc = postPath +  "/queryFieldList/index?serviceId=" + serviceId + "&serviceType=" + serviceType + "&grade=" + grade + "&paramType=1&operateMethod=add";
        openModal(frameSrc);
        closeModal();
    });

    // here is update button , send all selected rowList in url
    $("#btn_queryUpdate").click(function () {
        var rowList = $("#tb_queryfieldList").bootstrapTable("getSelections");
        console.log("luowen select rowList", rowList)
        var jsonDataList= encode_utf8(JSON.stringify(rowList));

        var framesrc = postPath + "/queryFieldList/index?serviceId=" + serviceId + "&serviceType=" + serviceType + "&grade=" + grade + "&paramType=1" + "&operateMethod=update&jsonDataList=" + jsonDataList;
        console.log("framesrc ", framesrc)
        openModal(framesrc);
        closeModal();
    });


    /*****************End 动态查询列配置**********************/

    /*****************Begin 固定查询列配置**********************/
    //查询显示字段列表
    $("#tb_querysfieldList").bootstrapTable('destroy').bootstrapTable({
        url: postPath + '/system/queryfield/getQueryFieldList',
        undefinedText: '-',
        striped: true, // 是否显示行间隔色
        queryParams: {serviceId: serviceId, serviceType: serviceType, grade: grade, paramType: 2},
        showColumns: false, // 显示隐藏列
        showRefresh: false, // 显示刷新按钮
        uniqueId: "guid", // 每一行的唯一标识
        columns: [{
            field: 'state',
            checkbox: true,
            align: 'center',
            valign: 'middle'
        }, {
            title: '字段Code',
            field: 'fieldname',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '字段名称',
            field: 'fieldnameCn',
            align: 'left',
            valign: 'middle',
            sortable: false
        }, {
            title: '字段类型',
            field: 'fieldtype',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '参数条件',
            field: 'parametercondition',
            align: 'center',
            valign: 'middle',
            sortable: false
        }, {
            title: '参数值',
            field: 'parametervalue',
            align: 'left',
            valign: 'middle',
            width: '100px',
            sortable: false
        }]
    });


    //新增固定查询列操作
    $("#btn_querysAdd").click(function () {
        var frameSrc = postPath + "/queryFieldList/index?serviceId=" + serviceId + "&serviceType=" + serviceType + "&grade=" + grade + "&paramType=2&operateMethod=add&conditionType=staticCondition";
        openModal(frameSrc);
        closeModal();
    });

    $("#btn_querysUpdate").click(function () {
        var rowList = $("#tb_querysfieldList").bootstrapTable("getSelections");
        console.log("luowen select rowList", rowList)
        var jsonDataList= encode_utf8(JSON.stringify(rowList));

        var framesrc = postPath + "/queryFieldList/index?serviceId=" + serviceId + "&serviceType=" + serviceType + "&grade=" + grade + "&paramType=1" + "&operateMethod=update&conditionType=staticCondition&jsonDataList=" + jsonDataList;
        console.log("framesrc ", framesrc)
        openModal(framesrc);
        closeModal();
    });


    //删除固定查询列
    $("#btn_querysDel").click(function () {
        var row = $('#tb_querysfieldList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        }

        var message = "";
        row.forEach( e => {
            message += e.fieldname + ", " + e.fieldnameCn + "<br/>";
        })

        var deleteFunction = function (result) {
            if (result == false)
                return;
            var keys = "";
            $.each(row, function (i, e) {
                keys += e.guid + "@";
            });
            keys = keys.substring(0, keys.length - 1);
            $.ajax({
                url: postPath + '/system/queryfield/deleteQueryfield',
                type: 'POST',
                data: {guids: keys},
                success: function (res) {
                    if (res > 0) {
                        $('#tb_querysfieldList').bootstrapTable('refresh');
                        getQuerysql();
                        // bootbox.alert("删除成功!");
                        showMsg('删除成功!', 'success');
                    } else {
                        // bootbox.alert("删除失败!");
                        showMsg('删除失败!', 'error');
                    }
                },
                error: function () {
                    // bootbox.alert("删除失败!");
                    showMsg('删除失败!', 'error');
                }
            });
        };

        confirmDelete(message, deleteFunction);
    });

    /*****************End 固定查询列配置**********************/

    /*****************Begin 在父级打开模态框**********************/
    //打开模态框
    function openModal(frameSrc) {
        var fatherBody = $(window.parent.document.body);
        var id = 'pagesModul';
        var dialog = $('#' + id);
        if (dialog.length == 0) {
            dialog = $('<div id="' + id + '" class="modal fade" tabindex="-1" aria-hidden="true">'
                + '<div id="pagesFieldDialog" >'
                + '<div class="modal-content">'
                + '<div class="modal-header" style="padding:8px; background-color:#4276A4;">'
                + '<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>'
                + '<span class="modal-title" style="color:#fff; font-size:16px;">字段列表</span>'
                + '</div>'
                + '<div class="modal-body">'
                + '<iframe id="ModelIframe"  name="ModelIframe"  style="width:97%; min-height:470px; border:solid 0px red;" src="' + frameSrc + '"></iframe>'
                + '</div>'
                + '</div>'
                + '</div></div>');
            dialog.appendTo(fatherBody);
        }
        dialog.modal({
            backdrop: false
        });
        var parentModul = $('#' + id, window.parent.document.body);

        fatherBody.append("<div id='backdropId' class='modal-backdrop fade in'></div>");

    }

    //关闭模态框
    function closeModal() {
        var fatherBody = $(window.parent.document.body);
        fatherBody.find("#pagesModul").on('hidden.bs.modal', function (e) {
            fatherBody.find("#backdropId").remove();
            fatherBody.find("#pagesModul").remove();
            $("#tb_queryfieldList").bootstrapTable('refresh');
            $('#tb_querysfieldList').bootstrapTable('refresh');
            getQuerysql();
        });
    }

    /*****************End 在父级打开模态框**********************/
    getQuerysql();

});

//设置sql文预览
function codeEdit() {
    var myTextArea = document.getElementById('code_editor');
    var myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
        lineNumbers: true,
        matchBrackets: true,
        styleActiveLine: true,
        height: '200px',
        theme: "neat",
        mode: 'velocity',
        readOnly: true
    });
}

var myTextArea = document.getElementById('code_editor');
var myCodeMirror = CodeMirror.fromTextArea(myTextArea, {
    lineNumbers: true,
    matchBrackets: true,
    styleActiveLine: true,
    lineWrapping: true,
    height: '200px',
    theme: "neat",
    mode: 'velocity',
    readOnly: true
});

//查询sql文
function getQuerysql() {
    var result = "";
    $.ajax({
        type: 'POST',
        url: postPath + '/system/queryfield/getQuerysql',
        data: {serviceId: serviceId, serviceType: serviceType, grade: grade},
        async: false,
        success: function (data) {
            result = data;
        }
    });
    result = result.replace(/>/g, ">\r");
    result = result.replace(/<\//g, "\r</");
    myCodeMirror.setValue(result);
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//动态条件-修改查询字段信息
function editQueryField(id) {
    var row = $('#tb_queryfieldList').bootstrapTable('getRowByUniqueId', id);
    $("#tb_queryfieldList").find("tr").each(function () {
        var trguid = $(this).attr("data-uniqueid");
        if (trguid == row.guid) {
            var nRow = $(this);
            var jqTds = $('>td', nRow);
            jqTds[4].innerHTML = '<input style="width:120px !important;" type="text" class="form-control input-small"  value="' + (row.parametercode == null ? "" : row.parametercode) + '">';
            jqTds[5].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                + '<option ' + (row.parametercondition == '=' ? "selected='selected'" : "") + ' value="=">=</option>'
                + '<option ' + (row.parametercondition == '!=' ? "selected='selected'" : "") + ' value="!=">!=</option>'
                + '<option ' + (row.parametercondition == '>' ? "selected='selected'" : "") + ' value=">">></option>'
                + '<option ' + (row.parametercondition == '>=' ? "selected='selected'" : "") + ' value=">=">>=</option>'
                + '<option ' + (row.parametercondition == '<' ? "selected='selected'" : "") + ' value="<"><</option>'
                + '<option ' + (row.parametercondition == '<=' ? "selected='selected'" : "") + ' value="<="><=</option>'
                + '<option ' + (row.parametercondition == '<=' ? "selected='selected'" : "") + ' value="<="><=</option>'
                + '<option ' + (row.parametercondition == 'like' ? "selected='selected'" : "") + ' value="like">like</option>'
                + '</select>';
            if (row.fieldtype == "date") {
                jqTds[6].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                    // +'<option '+(row.paramformat=='string'?"selected='selected'":"")+' value="string">string</option>'
                    // +'<option '+(row.paramformat=='int'?"selected='selected'":"")+' value="int">int</option>'
                    // +'<option '+(row.paramformat=='year'?"selected='selected'":"")+' value="year">year(yyyy)</option>'
                    // +'<option '+(row.paramformat=='month'?"selected='selected'":"")+' value="month">month</option>'
                    // +'<option '+(row.paramformat=='day'?"selected='selected'":"")+' value="day">day</option>'
                    //+'<option '+(row.paramformat=='ymonth'?"selected='selected'":"")+' value="ymonth">ymonth(yyyy-MM)</option>'
                    + '<option ' + (row.paramformat == 'date' ? "selected='selected'" : "") + ' value="date">date(yyyy-MM-dd)</option>'
                    // +'<option '+(row.paramformat=='datehour'?"selected='selected'":"")+' value="datehour">datehour(yyyy-MM-dd hh)</option>'
                    // +'<option '+(row.paramformat=='datehmin'?"selected='selected'":"")+' value="datehmin">datehmin(yyyy-MM-dd hh:mm)</option>'
                    + '<option ' + (row.paramformat == 'datetime' ? "selected='selected'" : "") + ' value="datetime">datetime(yyyy-MM-dd hh:mm:ss)</option>'
                    + '</select>';
            } else if (row.fieldtype == "string") {
                jqTds[6].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                    + '<option ' + (row.paramformat == 'string' ? "selected='selected'" : "") + ' value="string">string</option>'
                    //+'<option '+(row.paramformat=='int'?"selected='selected'":"")+' value="int">int</option>'
                    //+'<option '+(row.paramformat=='year'?"selected='selected'":"")+' value="year">year(yyyy)</option>'
                    // +'<option '+(row.paramformat=='month'?"selected='selected'":"")+' value="month">month</option>'
                    // +'<option '+(row.paramformat=='day'?"selected='selected'":"")+' value="day">day</option>'
                    // +'<option '+(row.paramformat=='ymonth'?"selected='selected'":"")+' value="ymonth">ymonth(yyyy-MM)</option>'
                    // +'<option '+(row.paramformat=='date'?"selected='selected'":"")+' value="date">date(yyyy-MM-dd)</option>'
                    // +'<option '+(row.paramformat=='datehour'?"selected='selected'":"")+' value="datehour">datehour(yyyy-MM-dd hh)</option>'
                    // +'<option '+(row.paramformat=='datehmin'?"selected='selected'":"")+' value="datehmin">datehmin(yyyy-MM-dd hh:mm)</option>'
                    // +'<option '+(row.paramformat=='datetime'?"selected='selected'":"")+' value="datetime">datetime(yyyy-MM-dd hh:mm:ss)</option>'
                    + '</select>';
            } else if (row.fieldtype == "int") {
                jqTds[6].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                    //+'<option '+(row.paramformat=='string'?"selected='selected'":"")+' value="string">string</option>'
                    + '<option ' + (row.paramformat == 'int' ? "selected='selected'" : "") + ' value="int">int</option>'
                    //+'<option '+(row.paramformat=='year'?"selected='selected'":"")+' value="year">year(yyyy)</option>'
                    // +'<option '+(row.paramformat=='month'?"selected='selected'":"")+' value="month">month</option>'
                    // +'<option '+(row.paramformat=='day'?"selected='selected'":"")+' value="day">day</option>'
                    // +'<option '+(row.paramformat=='ymonth'?"selected='selected'":"")+' value="ymonth">ymonth(yyyy-MM)</option>'
                    // +'<option '+(row.paramformat=='date'?"selected='selected'":"")+' value="date">date(yyyy-MM-dd)</option>'
                    // +'<option '+(row.paramformat=='datehour'?"selected='selected'":"")+' value="datehour">datehour(yyyy-MM-dd hh)</option>'
                    // +'<option '+(row.paramformat=='datehmin'?"selected='selected'":"")+' value="datehmin">datehmin(yyyy-MM-dd hh:mm)</option>'
                    // +'<option '+(row.paramformat=='datetime'?"selected='selected'":"")+' value="datetime">datetime(yyyy-MM-dd hh:mm:ss)</option>'
                    + '</select>';
            }

            jqTds[7].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                + '<option ' + (row.showtype == 0 ? "selected='selected'" : "") + ' value="0">文本框</option>'
                // +'<option '+(row.showtype==1?"selected='selected'":"")+' value="1">下拉框</option>'
                // +'<option '+(row.showtype==2?"selected='selected'":"")+' value="2">单选按钮</option>'
                // +'<option '+(row.showtype==3?"selected='selected'":"")+' value="3">复选框</option>'
                // +'<option '+(row.showtype==4?"selected='selected'":"")+' value="4">日期框</option>'
                + '</select>';
            jqTds[8].innerHTML = '<input style="width:60px !important;" id="touchspin_1" type="text" value="' + (row.queryorder == null ? "0" : row.queryorder) + '">';
        }
    });
    $("#touchspin_1").TouchSpin({
        verticalbuttons: true
    });
}

//动态条件-保存修改后查询字段信息
function saveQueryField(id) {
    var row = $('#tb_queryfieldList').bootstrapTable('getRowByUniqueId', id);
    $("#tb_queryfieldList").find("tr").each(function () {
        var trguid = $(this).attr("data-uniqueid");
        if (trguid == row.guid) {
            var nRow = $(this);
            var jqTds = $('>td', nRow);
            var midffvalue = $(':input', nRow);
            var temp = {
                guid: row.guid,
                serviceid: serviceId,
                parametercode: midffvalue[1].value,
                parametercondition: midffvalue[2].value,
                paramformat: midffvalue[3].value,
                queryorder: midffvalue[5].value,
                showtype: midffvalue[4].value,
                servicetype: serviceType,
                grade: grade
            };
            $.ajax({
                type: 'POST',
                url: postPath + '/system/queryfield/updateQueryfield',
                async: false,
                data: JSON.stringify(temp),
                dataType: 'json',
                contentType: "application/json",
                success: function (data) {
                    $("#tb_queryfieldList").bootstrapTable('refresh');
                    getQuerysql();
                }
            });
        }
    });
}

//固定条件-修改查询字段信息
function editQuerysField(id) {
    var row = $('#tb_querysfieldList').bootstrapTable('getRowByUniqueId', id);
    $("#tb_querysfieldList").find("tr").each(function () {
        var trguid = $(this).attr("data-uniqueid");
        if (trguid == row.guid) {
            var nRow = $(this);
            var jqTds = $('>td', nRow);
            jqTds[4].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                + '<option ' + (row.parametercondition == '=' ? "selected='selected'" : "") + ' value="=">=</option>'
                + '<option ' + (row.parametercondition == '!=' ? "selected='selected'" : "") + ' value="!=">!=</option>'
                + '<option ' + (row.parametercondition == '>' ? "selected='selected'" : "") + ' value=">">></option>'
                + '<option ' + (row.parametercondition == '>=' ? "selected='selected'" : "") + ' value=">=">>=</option>'
                + '<option ' + (row.parametercondition == '<' ? "selected='selected'" : "") + ' value="<"><</option>'
                + '<option ' + (row.parametercondition == '<=' ? "selected='selected'" : "") + ' value="<="><=</option>'
                + '<option ' + (row.parametercondition == '<=' ? "selected='selected'" : "") + ' value="<="><=</option>'
                + '<option ' + (row.parametercondition == 'like' ? "selected='selected'" : "") + ' value="like">like</option>'
                + '</select>';
            jqTds[5].innerHTML = '<input style="width:120px !important;" type="text" class="form-control input-small"  value="' + (row.parametervalue == null ? "" : row.parametervalue) + '">';
        }
    });
}

//固定条件-保存修改后查询字段信息
function saveQuerysField(id) {
    var row = $('#tb_querysfieldList').bootstrapTable('getRowByUniqueId', id);
    $("#tb_querysfieldList").find("tr").each(function () {
        var trguid = $(this).attr("data-uniqueid");
        if (trguid == row.guid) {
            var nRow = $(this);
            var jqTds = $('>td', nRow);
            var midffvalue = $(':input', nRow);
            var temp = {
                guid: row.guid,
                serviceid: serviceId,
                parametercondition: midffvalue[1].value,
                parametervalue: midffvalue[2].value,
                servicetype: serviceType,
                grade: grade
            };
            $.ajax({
                type: 'POST',
                url: postPath + '/system/queryfield/updateQueryfield',
                async: false,
                data: JSON.stringify(temp),
                dataType: 'json',
                contentType: "application/json",
                success: function (data) {
                    $("#tb_querysfieldList").bootstrapTable('refresh');
                    getQuerysql();
                }
            });
        }
    });
}

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'bottom-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}


function encode_utf8(s) {
  return encodeURIComponent(s);
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}
